
import UIKit
import Alamofire
import HandyJSON
#if DEBUG
    var baseUrl = "http://testvpn.preproduce.net/"
#else
    var baseUrl = "https://vpn.leadfirmly.com/"
#endif
// 获取节点
private var nodeListUrl = "node/list"
// 获取vpn账号
private var nodeInfo = "node/info"

private var tempNowTime = "0"
public let sharedSessionManager: Alamofire.Session = {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 10
    return Alamofire.Session(configuration: configuration)
}()

class XWHttpTool: NSObject {
    // 节点请求
    public func getNodeList(successHandler:@escaping(_ dataDic:XWServerModel)->(),failureHandler:@escaping(_ failure:String)->()) {
        get(nodeListUrl, nil) { data in
            successHandler(data as! XWServerModel)
        } failureHandler: {errorString  in
            failureHandler("Request failed")
        }
    }
    public func getNodeInfo(_ parameters:[String:Any]?,successHandler:@escaping(_ dataDic:XWServerInfoModel)->(),failureHandler:@escaping(_ failure:String)->()){
        post(nodeInfo, parameters) { data in
            successHandler(data as! XWServerInfoModel)
        } failureHandler: { failure in
            failureHandler("Request failed")
        }

    }
    
}
extension XWHttpTool {
    // get
    private func get(_ urlString:String,_ parameters:[String:Any]?,successHandler:@escaping(_ dataDic:Any)->(),failureHandler:@escaping(_ failure:String)->()){
        tempNowTime = String(getNowTimeTimestamp())
        let headers:HTTPHeaders = [
            "app_id":getAppId(),
            "Content-Type": "application/json",
            "rts": tempNowTime,
            "encrypt":getEncrypRTS(params: [:])
        ]
        let httpRequestURL = baseUrl + urlString
        printLog(httpRequestURL)
        sharedSessionManager.request(httpRequestURL,method: .get,headers: headers).validate().responseJSON { (response) in
            if (response.error == nil) {
                let dic = response.value as! NSDictionary
                if dic["code"] as! String == "0"{
                    let dataString = dic["data"] as! String
                    let responseJSON = self.stringValueDic(XWEncryptTool.decrypt(content: dataString))
                    let model:XWServerModel = JSONDeserializer<XWServerModel>.deserializeFrom(dict: (responseJSON! as NSDictionary))!
                    successHandler(model)
                }else{
                    failureHandler(dic["code"] as! String)
                }
            }else{
                failureHandler("Server problem")
            }
            
        }
    }
    
    // post
    private func post(_ urlString:String,_ parameters:[String:Any]?,successHandler:@escaping(_ dataDic:Any)->(),failureHandler:@escaping(_ failure:String)->()){
        tempNowTime = String(getNowTimeTimestamp())
        let headers:HTTPHeaders = [
            "Content-Type": "application/json",
            "app_id":getAppId(),
            "rts":String(getNowTimeTimestamp()),
            "encrypt":getEncrypRTS(params: [:])
        ]
        let httpRequestURL = baseUrl + urlString
        let tempParameters:Dictionary = getEncryBody(params: parameters?["data"] as Any)
        sharedSessionManager.request(httpRequestURL,method:.post,parameters:tempParameters, encoding: JSONEncoding.default,headers: headers).validate().responseJSON { (response) in
            if (response.error == nil) {
               let dic = response.value as! NSDictionary
               if dic["code"] as! String == "0"{
                   let dataString = dic["data"] as! String
                   let responseJSON = self.stringValueDic(XWEncryptTool.decrypt(content: dataString))
                   let model:XWServerInfoModel = JSONDeserializer<XWServerInfoModel>.deserializeFrom(dict: (responseJSON! as NSDictionary))!
                   successHandler(model)
               }else{
                   failureHandler(dic["code"] as! String)
               }
            }else{
                failureHandler("Server problem")
            }
        }
    }
    
    private func getEncrypRTS(params: [String:Any]) -> String {
        var additionalParameters = fillParams(temp: params)
        let sign = MD5(AIRequestTool.calculateSignValue(additionalParameters,appKey: getAppKey())).lowercased()
        additionalParameters["sign"] = sign
        return XWEncryptTool.encrypt(content: additionalParameters)
    }
    
    private func getEncryBody(params:Any) -> [String:Any] {
        var additionalParameters = ["rts":tempNowTime]
        additionalParameters["data"] = XWEncryptTool.convertToJSONString(object: params)
        let sign = MD5(AIRequestTool.calculateSignValue(additionalParameters,appKey: getAppKey())).lowercased()
        additionalParameters["sign"] = sign
        return ["data":XWEncryptTool.encrypt(content: additionalParameters)]
    }
    ///拼装params
    private func fillParams(temp:[String:Any]) -> [String:Any] {
        var additionalParameters:[String:Any] = ["dev_id":getUUID()]
        additionalParameters["brand"] = getDeviceBrand()
        additionalParameters["mac"] = AIRequestTool.getIPAddress(true)
        additionalParameters["app_ver_name"] = AIRequestTool.curAppVersion()
        additionalParameters["lang"] = getCurrentLanguage()
        additionalParameters["rts"] = tempNowTime
        additionalParameters["network_state"] = getNetwork()
        additionalParameters["model"] = getDeviceModel()
        additionalParameters["os_ver_name"] = getVersion()
        for (key,value) in temp {
            additionalParameters[key] = value
        }
        return additionalParameters
    }
    // 字符串转字典
    private func stringValueDic(_ str: String) -> [String : Any]?{
        let data = str.data(using: String.Encoding.utf8)
        if let dict = try? JSONSerialization.jsonObject(with: data!,
                        options: .mutableContainers) as? [String : Any] {
            return dict
        }

        return nil
    }
}
